<template>
  <div>
    <el-form ref="assetForm" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <div class="anthor">
        <div class="anthor-info">
          <div id="module1">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>基本信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="名称" required prop="name">
                    <el-input v-model="formItem.name" placeholder="请输入名称" :maxlength="255" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="编码" prop="code">
                    <el-input v-model="formItem.code" placeholder="请输入编码" :maxlength="255">
                      <!-- <el-tooltip slot="suffix" effect="light" content="编码必须是唯一的，如果不设置编码，系统将按照您设置的规则自动生成编码" placement="top"> -->
                      <i slot="suffix" class="el-input__icon el-icon-question" title="编码必须是唯一的，如果不设置编码，系统将按照您设置的规则自动生成编码" />
                      <!-- </el-tooltip> -->
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="资产条码">
                    <el-input v-model="formItem.sequence" placeholder="请输入资产条码" :maxlength="255" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="位置">
                    <treeselect
                      v-model="formItem.locationCode"
                      :multiple="false"
                      :options="availableLocations"
                      placeholder="请选择位置"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="资产类型" required prop="typeCode">
                    <treeselect
                      v-model="formItem.typeCode"
                      :multiple="false"
                      :options="typeOptions"
                      placeholder="选择资产类型"
                      :disable-branch-nodes="true"
                      @input="inputType"
                      @select="selectType"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="使用部门">
                    <treeselect
                      v-model="formItem.orgId"
                      :multiple="false"
                      :options="availableOganizations"
                      placeholder="请选择使用部门"
                      @select="selcetOrg"
                      @input="inputOrg"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="使用人">
                    <el-input
                      v-model="formItem.userName"
                      placeholder="请选择使用人"
                      @focus="handleUserIconClick"
                    >
                      <!-- <i slot="suffix" class="el-input__icon el-icon-s-custom" @click="handleUserIconClick" /> -->
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="使用期限（月）">
                    <el-input-number v-model="formItem.month" :precision="2" :step="1" :max="1000000000" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="标准型号">
                    <el-input v-model="formItem.productName" placeholder="请选择标准化型号" :disabled="productNameDisabled && (formItem.typeCode===null || formItem.typeCode===undefined) " @focus="productSelDialogFormVisible = true">
                      <!-- <i slot="suffix" class="el-input__icon el-icon-edit" @click="productSelDialogFormVisible = true" /> -->
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="计量单位">
                    <el-input v-model="formItem.measureUnit" placeholder="请输入计量单位" :maxlength="255" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="金额">
                    <el-input-number v-model="formItem.money" :precision="2" :step="1" :max="1000000000" />
                  </el-form-item>
                </el-col>
                <el-col v-if="id!='-1'" :span="8">
                  <el-form-item label="资产创建时间" required prop="createTime">
                    <el-date-picker
                      v-model="formItem.createTime"
                      type="datetime"
                      placeholder="选择日期时间"
                      align="right"
                      :picker-options="pickerOptions"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col v-if="id!='-1'" :span="8">
                  <el-form-item label="资产更新时间" required prop="updateTime">
                    <el-date-picker
                      v-model="formItem.updateTime"
                      type="datetime"
                      placeholder="选择日期时间"
                      align="right"
                      :picker-options="pickerOptions"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="资产来源">
                    <el-select v-model="formItem.sourceCode" class="select_input" placeholder="请选择资产来源">
                      <el-option v-for="(item) in assetSource" :key="item.code" :label="item.text" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="资产状态">
                    <el-select v-model="formItem.statusCode" class="select_input" placeholder="请选择资产状态">
                      <el-option v-for="(item) in assetStatus" :key="item.code" :label="item.text" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div id="module2">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>维保信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="供应商">
                    <el-input v-model="formItem.manufacturerName" placeholder="请选择供应商" @focus="handleIconClick">
                      <!-- <i slot="suffix" class="el-input__icon el-icon-edit" @click="handleIconClick" /> -->
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="供应商联系人">
                    <el-input v-model="formItem.manufacturerPerson" :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="供应商联系电话">
                    <el-input v-model="formItem.manufacturerPhone" :disabled="true" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="维保开始时间">
                    <el-date-picker
                      v-model="formItem.maintenanceStart"
                      type="datetime"
                      placeholder="选择日期时间"
                      align="right"
                      :picker-options="pickerOptions"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维保结束时间">
                    <el-date-picker
                      v-model="formItem.maintenanceEnd"
                      type="datetime"
                      placeholder="选择日期时间"
                      align="right"
                      :picker-options="pickerOptions"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维保负责人">
                    <el-input v-model="formItem.maintenanceUserName" placeholder="请输入维保负责人" @focus="handleMaintenanceIconClick">
                      <!-- <i slot="suffix" class="el-input__icon el-icon-s-custom" @click="handleMaintenanceIconClick" /> -->
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="40">
                <el-col :span="24">
                  <el-form-item label="维保说明">
                    <el-input v-model="formItem.maintenanceNote" placeholder="请输入维保说明" :maxlength="1023" type="textarea" :rows="rows" :autosize="true" resize="none" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div id="module3">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>合同信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="合同名称">
                    <el-input v-model="formItem.contractName" placeholder="请选择合同" @focus="handleContractClick">
                      <!-- <i slot="suffix" class="el-input__icon el-icon-document" @click="handleContractClick" /> -->
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="合同编码">
                    <el-input v-model="formItem.contractCode" :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="供应商">
                    <el-input v-model="formItem.contract.manufacturerName" :disabled="true" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div id="module4">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>其他信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <div v-for="(eitem, index) in effictiveExtField" :key="index">
                  <el-col v-if="eitem.sequence <= 3" :span="8">
                    <div v-if="eitem.dataType === 'text' || eitem.dataType === 'textarea'">
                      <el-form-item
                        :label="eitem.name"
                        :prop="eitem.extColumn"
                        :rules="[{required: eitem.required, message: '此项为必填项', trigger: 'blur'},
                                 {
                                   validator: function(rule, value, callback) {
                                     let reg = new RegExp(eitem.validateRule)
                                     if (reg.test(value) === false) {
                                       callback('请输入正确的格式' + eitem.validateRule)
                                     } else {
                                       callback()
                                     }
                                   },
                                   trigger: 'blur'
                                 }]"
                      >
                        <div v-if="eitem.sequence === 1">
                          <el-input v-model="formItem.ext1" :type="eitem.dataType" />
                        </div>
                        <div v-if="eitem.sequence === 2">
                          <el-input v-model="formItem.ext2" :type="eitem.dataType" />
                        </div>
                        <div v-if="eitem.sequence === 3">
                          <el-input v-model="formItem.ext3" :type="eitem.dataType" />
                        </div>
                      </el-form-item>
                    </div>
                    <div v-if="eitem.dataType === 'droplist'">
                      <el-form-item :label="eitem.name" :prop="eitem.extColumn" :rules="{required: eitem.required, message: '此项为必填项', trigger: 'blur'}">
                        <div v-if="eitem.sequence === 1">
                          <el-select v-model="formItem.ext1" class="select_input" placeholder="请选择">
                            <el-option v-for="(item) in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </div>
                        <div v-if="eitem.sequence === 2">
                          <el-select v-model="formItem.ext2" class="select_input" placeholder="请选择">
                            <el-option v-for="(item) in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </div>
                        <div v-if="eitem.sequence === 3">
                          <el-select v-model="formItem.ext3" class="select_input" placeholder="请选择">
                            <el-option v-for="(item) in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </div>
                      </el-form-item>
                    </div>
                    <div v-if="eitem.dataType === 'multipledropdown'">
                      <div v-if="eitem.sequence === 1">
                        <el-form-item :label="eitem.name" prop="ext1Array" :rules="{required: eitem.required, type: 'array', min: 1, message: '此项为必填项', trigger: 'change'}">
                          <el-select v-model="formItem.ext1Array" multiple placeholder="请选择" @change="$forceUpdate()">
                            <el-option v-for="item in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </el-form-item>
                      </div>
                      <div v-if="eitem.sequence === 2">
                        <el-form-item :label="eitem.name" prop="ext2Array" :rules="{required: eitem.required, type: 'array', min: 1, message: '此项为必填项', trigger: 'change'}">
                          <el-select v-model="formItem.ext2Array" multiple placeholder="请选择" @change="$forceUpdate()">
                            <el-option v-for="item in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </el-form-item>
                      </div>
                      <div v-if="eitem.sequence === 3">
                        <el-form-item :label="eitem.name" prop="ext3Array" :rules="{required: eitem.required, type: 'array', min: 1, message: '此项为必填项', trigger: 'change'}">
                          <el-select v-model="formItem.ext3Array" multiple placeholder="请选择" @change="$forceUpdate()">
                            <el-option v-for="item in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                    <div v-if="eitem.dataType === 'dateselect'">
                      <el-form-item :label="eitem.name" :prop="eitem.extColumn" :rules="{required: eitem.required, message: '此项为必填项', trigger: 'blur'}">
                        <div v-if="eitem.sequence === 1">
                          <el-date-picker v-model="formItem.ext1" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" />
                        </div>
                        <div v-if="eitem.sequence === 2">
                          <el-date-picker v-model="formItem.ext2" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" />
                        </div>
                        <div v-if="eitem.sequence === 3">
                          <el-date-picker v-model="formItem.ext3" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" />
                        </div>
                      </el-form-item>
                    </div>
                  </el-col>
                </div>
              </el-row>
              <el-row :gutter="40">
                <div v-for="(eitem, index) in effictiveExtField" :key="index">
                  <el-col v-if="eitem.sequence > 3" :span="8">
                    <div v-if="eitem.dataType === 'text' || eitem.dataType === 'textarea'">
                      <el-form-item
                        :label="eitem.name"
                        :prop="eitem.extColumn"
                        :rules="[{required: eitem.required, message: '此项为必填项', trigger: 'blur'},
                                 {
                                   validator: function(rule, value, callback) {
                                     let reg = new RegExp(eitem.validateRule)
                                     if (reg.test(value) === false) {
                                       callback('请输入正确的格式' + eitem.validateRule)
                                     } else {
                                       callback()
                                     }
                                   },
                                   trigger: 'blur'
                                 }]"
                      >
                        <div v-if="eitem.sequence === 4">
                          <el-input v-model="formItem.ext4" :type="eitem.dataType" />
                        </div>
                        <div v-if="eitem.sequence === 5">
                          <el-input v-model="formItem.ext5" :type="eitem.dataType" />
                        </div>
                      </el-form-item>
                    </div>
                    <div v-if="eitem.dataType === 'droplist'">
                      <el-form-item :label="eitem.name" :prop="eitem.extColumn" :rules="{required: eitem.required, message: '此项为必填项', trigger: 'blur'}">
                        <div v-if="eitem.sequence === 4">
                          <el-select v-model="formItem.ext4" class="select_input" placeholder="请选择">
                            <el-option v-for="(item) in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </div>
                        <div v-if="eitem.sequence === 5">
                          <el-select v-model="formItem.ext5" class="select_input" placeholder="请选择">
                            <el-option v-for="(item) in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </div>
                      </el-form-item>
                    </div>
                    <div v-if="eitem.dataType === 'multipledropdown'">
                      <div v-if="eitem.sequence === 4">
                        <el-form-item :label="eitem.name" prop="ext4Array" :rules="{required: eitem.required, type: 'array', min: 1, message: '此项为必填项', trigger: 'change'}">
                          <el-select v-model="formItem.ext4Array" multiple placeholder="请选择" @change="$forceUpdate()">
                            <el-option v-for="item in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </el-form-item>
                      </div>
                      <div v-if="eitem.sequence === 5">
                        <el-form-item :label="eitem.name" prop="ext5Array" :rules="{required: eitem.required, type: 'array', min: 1, message: '此项为必填项', trigger: 'change'}">
                          <el-select v-model="formItem.ext5Array" multiple placeholder="请选择" @change="$forceUpdate()">
                            <el-option v-for="item in eitem.extDicData" :key="item.code" :label="item.text" :value="item.code" />
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                    <div v-if="eitem.dataType === 'dateselect'">
                      <el-form-item :label="eitem.name" :prop="eitem.extColumn" :rules="{required: eitem.required, message: '此项为必填项', trigger: 'blur'}">
                        <div v-if="eitem.sequence === 4">
                          <el-date-picker v-model="formItem.ext4" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" />
                        </div>
                        <div v-if="eitem.sequence === 5">
                          <el-date-picker v-model="formItem.ext5" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" />
                        </div>
                      </el-form-item>
                    </div>
                  </el-col>
                </div>
              </el-row>
            </div>
          </div>
          <anchor key="el-dialog__body" :xleft="1" :ytop="10" container=".el-dialog__body" :title-list="anchorList" />
        </div>
      </div></el-form>
    <SelectDialog v-if="manucacturerSelect" title="选择供应商" :append-to-body="true" :show="manucacturerSelect" @on-ok="selectManufaturerOk" @on-cancel="selectManufaturerCancel">
      <manufacturer ref="manfacturer" :status="true" :for-selection="true" :multiple-selected="true" /></SelectDialog>
    <SelectDialog v-if="mainteanceSelDialogFormVisible" title="选择维保负责人" :append-to-body="true" :show="mainteanceSelDialogFormVisible" @on-ok="selectMainteanceOk" @on-cancel="selectMainteanceCancel">
      <UsersPage ref="usersMainteance" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择使用人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.orgId" />
    </SelectDialog>
    <SelectDialog v-if="contractFormVisible" title="选择合同" :append-to-body="true" :show="contractFormVisible" @on-ok="selectContractOk" @on-cancel="selectContractCancel">
      <contract ref="contract" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
    <SelectDialog v-if="productSelDialogFormVisible" title="选择标准化产品" :show="productSelDialogFormVisible" :append-to-body="true" @on-ok="selectProductOk" @on-cancel="selectProductCancel">
      <product ref="type" :for-selection="true" :asset-type-code="formItem.typeCode" :multiple-selected="true" />
    </SelectDialog>
  </div>
</template>

<script>
import treeselect from '@neu/biz-core/components/TreeSelect'
import Anchor from '@neu/biz-core/components/Anchor/index'
import UsersPage from '@neu/auth-ui/views/users/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import { update, detail } from '@neu/dcam-ui/api/fixedAsset'
import { findByDictionaryType } from '@neu/dcam-ui/api/dictionary'
import { listEffective } from '@neu/dcam-ui/api/assetExtFieldConfig'
import { tree } from '@neu/dcam-ui/api/assetType'
import * as locationApi from '@neu/dcam-ui/api/location'
import * as organizations from '@neu/auth-ui/api/organization'
import manufacturer from '@neu/dcam-ui/views/manufacturer/tables'
import contract from '@neu/dcam-ui/views/contract/tables'
import product from '@neu/dcam-ui/views/product'
import { formatDate } from '@neu/biz-core/utils/utils'

import { create } from '@neu/dcam-ui/api/inventoryResult'

// 定义一个表单原始项
const formItem = {
  name: '',
  code: '',
  typeCode: null,
  sequence: '',
  locationCode: null,
  productId: '',
  productName: '',
  measureUnit: '',
  money: '',
  orgId: null,
  orgName: '',
  userId: '',
  userName: '',
  month: '',
  manufacturerId: '',
  manufacturerName: '',
  manufacturerPerson: '',
  manufacturerPhone: '',
  maintenanceId: '',
  maintenanceStart: null,
  maintenanceEnd: null,
  maintenanceUserId: '',
  maintenanceUserName: '',
  maintenanceNote: '',
  contractCode: '',
  contractName: '',
  contract: {},
  createTime: '',
  updateTime: '',
  sourceCode: '',
  statusCode: '',
  ext1: '',
  ext1Array: [],
  ext2: '',
  ext2Array: [],
  ext3: '',
  ext3Array: [],
  ext4: '',
  ext4Array: [],
  ext5: '',
  ext5Array: [],
  dutyId: '',
  status: 'idle',
  dutyResultStatus: 'gain'
}
export default {
  name: 'FixedAssetEditFormPage',
  components: {
    Anchor,
    manufacturer,
    UsersPage,
    SelectDialog,
    contract,
    treeselect,
    product
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },

  data() {
    return {
      anchorList: [ // 锚点列表
        { id: 'module1', label: '基本信息' },
        { id: 'module2', label: '维保信息' },
        { id: 'module3', label: '合同信息' },
        { id: 'module4', label: '其他信息' }
      ],
      /** 规格型号disable */
      productNameDisabled: true,
      /** 是否显示产品信息 */
      productSelDialogFormVisible: false,
      /** 资产来源 */
      assetSource: [],
      /** 资产状态 */
      assetStatus: [],
      /** 有效扩展属性 */
      effictiveExtField: [],
      /** 是否显示合同信息 */
      contractFormVisible: false,
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      /** 是否显示维保负责人的数据 */
      mainteanceSelDialogFormVisible: false,
      /** 维保信息对话框是否显示 */
      manucacturerSelect: false,
      /** 资产位置树 */
      availableLocations: [],
      /** 资产类型树 */
      typeOptions: [],
      /** 使用部门 */
      availableOganizations: [],
      /** 是否初始化 */
      isUpdateInit: true,
      /** 行数 */
      rows: 2,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        // sequence: [{ required: true, message: '序列号不能为空', trigger: 'blur' }],
        // code: [{ required: true, message: '标识不能为空', trigger: 'blur' }],
        typeCode: [{ required: true, message: '选择类型', trigger: 'change' }],
        createTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        updateTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    tree().then(response => {
      const result = response.data
      this.typeOptions = result
    })
    locationApi.tree().then(response => {
      this.availableLocations = response.data
    })
    organizations.tree().then(response => {
      this.availableOganizations = [response.data]
    })
    findByDictionaryType('assetSource').then(response => {
      this.assetSource = response.data
    })
    findByDictionaryType('assetStatus').then(response => {
      this.assetStatus = response.data
    })
    listEffective().then(response => {
      this.effictiveExtField = response.data
    })
    this.formItem.dutyId = this.$route.query.dutyId
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          this.formItem = { ... response.data }
          if (this.formItem.contract === null) {
            this.formItem.contract = {}
          }

          this.formItem.ext1Array = this.formItem.ext1 && this.formItem.ext1.indexOf('[') !== -1 ? JSON.parse(this.formItem.ext1) : ''
          this.formItem.ext2Array = this.formItem.ext2 && this.formItem.ext2.indexOf('[') !== -1 ? JSON.parse(this.formItem.ext2) : ''
          this.formItem.ext3Array = this.formItem.ext3 && this.formItem.ext3.indexOf('[') !== -1 ? JSON.parse(this.formItem.ext3) : ''
          this.formItem.ext4Array = this.formItem.ext4 && this.formItem.ext4.indexOf('[') !== -1 ? JSON.parse(this.formItem.ext4) : ''
          this.formItem.ext5Array = this.formItem.ext5 && this.formItem.ext5.indexOf('[') !== -1 ? JSON.parse(this.formItem.ext5) : ''
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    selectType() {

    },
    inputType(value) {
      if (value === undefined) {
        this.formItem.productName = ''
        this.productNameDisabled = true
      } else {
        this.productNameDisabled = false
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      this.formItem.ext1 = this.formItem.ext1Array.length > 0 ? JSON.stringify(this.formItem.ext1Array) : this.formItem.ext1
      this.formItem.ext2 = this.formItem.ext2Array.length > 0 ? JSON.stringify(this.formItem.ext2Array) : this.formItem.ext2
      this.formItem.ext3 = this.formItem.ext3Array.length > 0 ? JSON.stringify(this.formItem.ext3Array) : this.formItem.ext3
      this.formItem.ext4 = this.formItem.ext4Array.length > 0 ? JSON.stringify(this.formItem.ext4Array) : this.formItem.ext4
      this.formItem.ext5 = this.formItem.ext5Array.length > 0 ? JSON.stringify(this.formItem.ext5Array) : this.formItem.ext5

      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.assetForm.validate((valid) => {
          if (valid) {
            if (formatDate(this.formItem.maintenanceStart) > formatDate(this.formItem.maintenanceEnd)) {
              return this.$message({
                showClose: true,
                message: '维保开始时间大于维保结束时间',
                type: 'error'
              })
            }
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.assetForm.resetFields()
      this.formItem = { ...formItem }
    },
    /** 选择供货商 */
    handleIconClick() {
      this.manucacturerSelect = true
    },
    selectManufaturerCancel() {
      this.manucacturerSelect = false
    },
    selectManufaturerOk() {
      var manufacturers = this.$refs.manfacturer.selections
      if (manufacturers.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个供应商',
          type: 'error'
        })
      }
      if (manufacturers.length < 1) {
        this.formItem.manufacturerId = ''
        this.formItem.manufacturerName = ''
        this.formItem.manufacturerPerson = ''
        this.formItem.manufacturerPhone = ''
      } else {
        this.formItem.manufacturerId = manufacturers[0].id
        this.formItem.manufacturerName = manufacturers[0].name
        this.formItem.manufacturerPerson = manufacturers[0].person
        this.formItem.manufacturerPhone = manufacturers[0].phone
      }

      this.manucacturerSelect = false
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      if (!this.formItem.orgId) {
        this.$message({
          type: 'warning',
          message: '请选择使用部门!'
        })
        return
      }
      this.userSelDialogFormVisible = true
    },
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个用户',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.userId = ''
        this.formItem.userName = ''
      } else {
        this.formItem.userId = users[0].username
        this.formItem.userName = users[0].name ? users[0].name : users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    /** 组织机构赋值 */
    selcetOrg(value) {
      this.formItem.orgName = value.title
    },
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.formItem.userId = ''
        this.formItem.userName = ''
      }
      this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.orgName = ''
      }
    },
    /** 选择维保负责人 */
    handleMaintenanceIconClick() {
      this.mainteanceSelDialogFormVisible = true
    },
    selectMainteanceOk() {
      var mainteanceUsers = this.$refs.usersMainteance.selections
      if (mainteanceUsers.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个用户',
          type: 'error'
        })
      }
      if (mainteanceUsers.length < 1) {
        this.formItem.maintenanceUserName = ''
        this.formItem.maintenanceUserId = ''
      } else {
        this.formItem.maintenanceUserId = mainteanceUsers[0].username
        this.formItem.maintenanceUserName = mainteanceUsers[0].name ? mainteanceUsers[0].name : mainteanceUsers[0].username
      }
      this.mainteanceSelDialogFormVisible = false
    },
    selectMainteanceCancel() {
      this.mainteanceSelDialogFormVisible = false
    },
    /** 合同信息 */
    handleContractClick() {
      this.contractFormVisible = true
    },
    selectContractOk() {
      var selectContract = this.$refs.contract.selections
      console.log(selectContract)
      if (selectContract.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个合同',
          type: 'error'
        })
      }
      if (selectContract.length < 1) {
        this.formItem.contractName = ''
        this.formItem.contractCode = ''
        this.formItem.contract['manufacturerName'] = ''
      } else {
        this.formItem.contract['manufacturerName'] = selectContract[0].manufacturerName
        this.formItem.contractName = selectContract[0].name
        this.formItem.contractCode = selectContract[0].code
      }
      this.contractFormVisible = false
    },
    selectContractCancel() {
      this.contractFormVisible = false
    },
    // 产品选择OK
    selectProductOk() {
      const selections = this.$refs.type.selections
      if (selections.length !== 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个标准化产品',
          type: 'error'
        })
      } else {
        this.formItem.productId = selections[0].id
        this.formItem.name = selections[0].name
        this.formItem.money = selections[0].money
        this.formItem.measureUnit = selections[0].measureUnit
        this.formItem.productName = selections[0].specification
        this.productSelDialogFormVisible = false
      }
    },
    // 产品选择取消
    selectProductCancel() {
      this.productSelDialogFormVisible = false
    }
  }
}
</script>
